/*
	Assignment 5a : Producer and Consumer using Semaphore
	Name : Rushikesh Mukund Fanse
	Roll No : 16
	Div : H
*/
#include<pthread.h>
#include<cstdio>
#include<iostream>
#include<semaphore.h>
#include<cstdlib>
#include<vector>
#include<unistd.h>
using namespace std;
sem_t mutex,full,empty;
vector<int> basket(5);
int produce_item()
{
	int item=rand()%11;
	cout<<"item produced "<<item<<endl;
	return item;
}
int consume_item(int item)
{
	basket.pop_back();
	cout<<"item consumed "<<item<<endl;
}
void put_into_basket(int item)
{
	sleep(2);
	basket.push_back(item);	
}
int get_from_basket()
{
	sleep(2);
	return basket.back();
}
void*producer(void*)
{
	int item;
	while(true)
	{
		item=produce_item();
		sem_wait(&empty);//decrement the empty count as the basket is recieving an element 
		sem_wait(&mutex);//critical section as the item is to be put into basket
		put_into_basket(item);//item in basket
		sem_post(&mutex);//critical section ends unlock the basket for consumer
		sem_post(&full);//increment the full count as the basket is getting full an indicate the consumer tha it can consume
	}
		
}
void*consumer(void*)
{
	int item;
	while(true)
	{
		sem_wait(&full);//decrement the empty count as the item is basket is going to be consumed
		sem_wait(&mutex);//critical section we are removing item from basket
		item=get_from_basket();//we recieve item from the basket
		sem_post(&mutex);//critical section ends we unlock the basket for item consumption
		sem_post(&empty);//increment the empty count as the item is consumed  
		consume_item(item);
	}
}
int main()
{
	pthread_t t1;
	pthread_t t2;
	sem_init(&mutex,1,1);
	sem_init(&full,1,0);
	sem_init(&empty,1,5);
	pthread_create(&t1,NULL,producer,NULL);
	pthread_create(&t2,NULL,consumer,NULL);
	pthread_join(t1,NULL);
	pthread_join(t2,NULL);
	sem_destroy(&mutex);
	sem_destroy(&full);
	sem_destroy(&empty);
	return 0;
}
/*
rishi@rishi-PC:~$ ./a.out
item produced 6
item produced 10
item produced 6
item produced 2
item produced 1
item produced 4
item consumed 1
item consumed 2
item consumed 6
item consumed 10
item consumed 6
item produced 0
item produced 6
item produced 3
item produced 1
item produced 8
item consumed 1
item consumed 3
item produced 7
item produced 5
item consumed 7
item consumed 8
item consumed 6
item consumed 0
item consumed 4
item produced 3
item produced 7
item produced 4
item produced 9
item produced 10
item consumed 9
item consumed 4
item consumed 7
item consumed 3
item consumed 5
item produced 2

*/
